import json
import random
import string
import time
import logging
import os
import pypinyin
from logging.handlers import RotatingFileHandler

import requests
from flask import Blueprint, request, jsonify
from pypinyin.core import lazy_pinyin

from app.modules1.PublicApproach import get_token_result
from app.modules1.common.encryptionUtils import getResult1

# 创建蓝图
vendinfo_bp = Blueprint('vendinfo', __name__)

# 配置供应商专用日志
vendor_logger = logging.getLogger('vendor_operations')
vendor_logger.setLevel(logging.INFO)

# 创建日志目录
log_dir = os.path.dirname(os.path.abspath(__file__))
log_file_path = os.path.join(log_dir, 'vendor_operations.log')

# 创建文件处理器
vendor_handler = RotatingFileHandler(
    log_file_path,
    maxBytes=5000000,  # 5MB
    backupCount=3,
    encoding='utf-8'
)
vendor_handler.setFormatter(logging.Formatter(
    '%(asctime)s - %(levelname)s - %(message)s'
))
vendor_logger.addHandler(vendor_handler)

# 通用日志
logger = logging.getLogger(__name__)


@vendinfo_bp.route('/vendor/add', methods=['POST'])
def add_vendor_info():
    """
    新增供应商接口
    """
    try:
        # 检查请求内容类型
        if not request.is_json:
            logger.error(f'请求内容类型错误: {request.content_type}')
            return jsonify({
                'success': False,
                'message': '请求必须是JSON格式'
            }), 400

        # 获取原始数据用于调试
        raw_data = request.get_data(as_text=True)
        # logger.info(f'接收到的原始数据: {raw_data}')

        # 获取请求数据
        try:
            request_data = request.get_json()
        except Exception as json_error:
            logger.error(f'JSON解析失败: {str(json_error)}, 原始数据: {raw_data}')
            return jsonify({
                'success': False,
                'message': f'JSON格式错误: {str(json_error)}'
            }), 400

        # 检查请求数据是否为空
        if not request_data:
            logger.error('请求数据为空')
            return jsonify({
                'success': False,
                'message': '请求数据不能为空'
            }), 400

        logger.info(f'新增供应商请求数据: {request_data}')

        # 验证必填字段
        required_fields = ['name', 'code', 'leader', 'tel', 'field1', 'field3', 'field4', 'field5', 'field8', 'field12']
        missing_fields = []
        for field in required_fields:
            value = request_data.get(field)
            if not value or (isinstance(value, str) and not value.strip()):
                missing_fields.append(field)

        if missing_fields:
            error_msg = f'缺少必填字段: {", ".join(missing_fields)}'
            logger.error(error_msg)
            return jsonify({
                'success': False,
                'message': error_msg
            }), 400

        # 调用添加供应商函数
        result = add_vendor_info_internal(request_data)

        # 记录操作结果到专用日志
        vendor_name = request_data.get('name', '未知供应商')
        vendor_code = request_data.get('code', '未知编码')

        if result['success']:
            vendor_logger.info(
                f'供应商创建成功 - 名称: {vendor_name}, 编码: {vendor_code}, 负责人: {request_data.get("leader", "未知")}, 电话: {request_data.get("tel", "未知")}')
            return result, 200
        else:
            vendor_logger.error(
                f'供应商创建失败 - 名称: {vendor_name}, 编码: {vendor_code}, 错误信息: {result.get("message", "未知错误")}')
            return result, 500

    except Exception as e:
        logger.error(f'新增供应商接口处理过程中发生错误: {str(e)}', exc_info=True)
        return jsonify({
            'success': False,
            'message': f'服务器错误: {str(e)}'
        }), 500


@vendinfo_bp.route('/vendor/bank_data', methods=['POST'])
def add_vendor_bank_data():
    """
    新增供应商收款账户接口
    """
    try:
        # 检查请求内容类型
        if not request.is_json:
            logger.error(f'请求内容类型错误: {request.content_type}')
            return jsonify({
                'success': False,
                'message': '请求必须是JSON格式'
            }), 400

        # 获取请求数据
        try:
            request_data = request.get_json()
        except Exception as json_error:
            raw_data = request.get_data(as_text=True)
            logger.error(f'JSON解析失败: {str(json_error)}, 原始数据: {raw_data}')
            return jsonify({
                'success': False,
                'message': f'JSON格式错误: {str(json_error)}'
            }), 400

        # 检查请求数据是否为空
        if not request_data:
            logger.error('请求数据为空')
            return jsonify({
                'success': False,
                'message': '请求数据不能为空'
            }), 400

        logger.info(f'新增供应商收款账户请求数据: {request_data}')

        # 验证必填字段
        required_fields = ['accName', 'bankacct', 'bankbranch', 'bankName', 'vendId']
        missing_fields = [field for field in required_fields if not request_data.get(field) or (
                    isinstance(request_data.get(field), str) and not request_data.get(field).strip())]

        if missing_fields:
            error_msg = f'缺少必填字段: {", ".join(missing_fields)}'
            logger.error(error_msg)
            return jsonify({
                'success': False,
                'message': error_msg
            }), 400

        # 调用添加供应商收款账户函数
        result = add_Payaccountcreate(request_data)

        # 提取日志字段
        acc_name = request_data.get('accName', 'N/A')
        bank_acct = request_data.get('bankacct', 'N/A')
        bank_name = request_data.get('bankName', 'N/A')
        bank_branch = request_data.get('bankbranch', 'N/A')
        vend_id = request_data.get('vendId', 'N/A')

        # 记录操作结果到专用日志
        log_info = (
            f"账户名称: {acc_name}, "
            f"账户编码: {bank_acct}, "
            f"银行名称: {bank_name}, "
            f"银行账户: {bank_acct}, "
            f"银行开户行: {bank_branch}, "
            f"供应商ID: {vend_id}"
        )

        if result['success']:
            vendor_logger.info(f'供应商收款账户创建成功 - {log_info}')
            return result, 200
        else:
            vendor_logger.error(f'供应商收款账户创建失败 - {log_info}')
            return result, 500

    except Exception as e:
        logger.exception("处理供应商收款账户新增请求时发生未预期异常")
        return jsonify({
            'success': False,
            'message': '服务器内部错误'
        }), 500


def add_vendor_info_internal(vendor_data):
    try:
        token = get_token_result()
        # logger.info(f'获取到token: {token}')
        url = "https://env3.jkyservice.com/jkyun/erp/vendinfo/save"
        headers = {
            "authority": "env3.jkyservice.com",
            "method": "POST",
            "path": "/jkyun/erp/vendinfo/save",
            "scheme": "https",
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "zh-CN,zh;q=0.9",
            "module_code": "supplier_list_new_list",
            "origin": "https://env3.jkyservice.com",
            "priority": "u=1, i",
            # "referer": "https://env3.jkyservice.com/erp/customer_provider/provider_add1.html?_winid=w4722&_t=609834"
        }
        # 构造必要字段
        name = vendor_data.get("name")
        # acronyms为name的拼音首字母小写
        acronyms = ''.join(lazy_pinyin(name, style=pypinyin.Style.FIRST_LETTER)).lower()
        code = vendor_data.get("code")
        # 当前时间
        developDate = time.strftime("%Y-%m-%d", time.localtime())
        # 供应商负责人
        leader = vendor_data.get("leader")
        # 获取手机号
        tel = vendor_data.get("tel")
        # 必填字段，不设置默认值
        # 售后情况
        field1 = vendor_data.get("field1")
        # 送货方式
        field3 = vendor_data.get("field3")
        # 保证金
        field4 = vendor_data.get("field4")
        # 开票方式
        field5 = vendor_data.get("field5")
        # 账期
        field8 = vendor_data.get("field8")
        # 产品经理
        field9 = vendor_data.get("field9")
        # 送货方式
        field12 = vendor_data.get("field12")
        # 供应商建档特别提醒
        remindMsg = vendor_data.get("remindMsg")
        # 图片数组处理
        fileUrl = vendor_data.get("fileUrl")
        vendInfoFile = []

        # 只有当fileUrl存在且不为空时才添加文件信息
        if fileUrl and fileUrl.strip():
            random_name = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
            file_id = ''.join(random.choices(string.digits, k=19))
            fileKey = f"longterm/547517112768259072/system/erp/2086410132235618432/{file_id}.png"
            file_name = f"{random_name}.png"
            vendInfoFile = [{
                "fileName": file_name,
                "fileKey": fileKey,
                "fileUrl": fileUrl.strip()
            }]

        data = {"vendInfoJsonstr": {
            "estimatedProductionUnit": "单",
            "classId": "62",
            "code": code,
            "name": name,
            "acronyms": acronyms,
            "abbreviation": "",
            # "assistantCode": "xzgys",
            "developDate": developDate,
            "leader": leader,
            "tel": tel,
            "purchOfGoods": "0",
            "outsourcedFactory": "0",
            "ownFactory": "0",
            "outsourcedManagedWarehouse": "0",
            "logisiticService": "0",
            "isAssembler": "0",
            "remindMsg": remindMsg,
            "orderIndex": 0,
            "purchOfficeId": "2013772604744992000",
            "currencyCode": "CNY",
            "field1": field1,
            "field3": field3,
            "field4": field4,
            "field5": field5,
            "field8": field8,
            "field9": field9,
            "field12": field12,
            "flagData": "",
            "countryName": "中国",
            "provinceName": "",
            "countryId": "555",
            "className": "正常合作",
            "applyName": field9,
            "companyName": "新疆最西域电子商务有限公司",
            "companyId": "1924002902255536000",
            "departName": "供应链中心",
            "departId": "2104413733825447296",
            "purchOfficeName": "供应链产品服务部",
            "currencyName": "人民币",
            "vendInfoFile": vendInfoFile
        }}
        logger.info(f'构造的数据: {data}')
        data['vendInfoJsonstr'] = json.dumps(data['vendInfoJsonstr'])
        requests_data = getResult1(token, data)
        # logger.info(f'签名数据获取成功')
        r = requests.post(url, headers=headers, data=requests_data)
        logger.info(f'请求响应状态码: {r.status_code}')

        # 解析响应并返回结果
        try:
            response_json = r.json()
            return {
                'success': True,
                'message': '供应商添加成功',
                'data': response_json
            }
        except:
            return {
                'success': r.status_code == 200,
                'message': '供应商添加完成',
                'data': r.text
            }

    except Exception as e:
        error_msg = f'供应商添加失败: {str(e)}'
        logger.error(f'add_vendor_info_internal函数执行失败: {str(e)}', exc_info=True)

        # 记录到专用日志
        vendor_name = vendor_data.get('name', '未知供应商')
        vendor_code = vendor_data.get('code', '未知编码')
        vendor_logger.error(f'供应商创建异常 - 名称: {vendor_name}, 编码: {vendor_code}, 异常信息: {str(e)}')

        return {
            'success': False,
            'message': error_msg
        }


# 收款账户新增
def add_Payaccountcreate(bank_data):
    token = get_token_result()
    # logger.info(f'获取到token: {token}')
    url = "https://env3.jkyservice.com/jkyun/erp/vendinfo/payaccountcreate"
    headers = {
        "authority": "env3.jkyservice.com",
        "method": "POST",
        "path": "/jkyun/erp/vendinfo/payaccountcreate",
        "scheme": "https",
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br, zstd",
        "accept-language": "zh-CN,zh;q=0.9",
        "module_code": "supplier_list_new_list",
        "origin": "https://env3.jkyservice.com",
        "priority": "u=1, i",
    }
    # 构造必要字段
    # 公司名称
    accName = bank_data.get("accName")
    # 银行账号
    bankacct = bank_data.get("bankacct")
    # 开户行
    bankbranch = bank_data.get("bankbranch")
    # 银行名称
    bankName = bank_data.get("bankName")
    # 供应商ID
    vendId = bank_data.get("vendId")
    data = {
        "vendInfoJsonstr": {
            "accountTypeName": "银行",
            "accName": accName,
            "bankacct": bankacct,
            "bankbranch": bankbranch,
            "bankCode": "BOC",
            "internationalBankAccount": "",
            "swiftCode": "",
            "countriesRegions": "",
            "isDefault": "0",
            "accountTypeCode": "BANK",
            "vendId": vendId,
            "bankName": bankName
        }
    }
    logger.info(f'构造的数据: {data}')
    data['vendInfoJsonstr'] = json.dumps(data['vendInfoJsonstr'])
    requests_data = getResult1(token, data)
    print(requests_data)
    # logger.info(f'签名数据获取成功')
    r = requests.post(url, headers=headers, data=requests_data)
    logger.info(f'请求响应状态码: {r.status_code}')
    return r.json()


if __name__ == '__main__':
    # test_vendor_data ={
    #     "name": "测试供应商111",
    #     "code": "ZXY0008",
    #     "leader": "张三",
    #     "tel": "12345678901",
    #     "field1": "无",
    #     "field3": "含运到仓",
    #     "field4": "200",
    #     "field5": "普票",
    #     "field8": "月结",
    #     "field9": "王雪",
    #     "field12": "能卸货",
    #     "remindMsg": "测试，不要审核",
    #     "fileUrl": "https://qingflow.com/api/storage/file/qingflow-uploads-prod/documents/data/invite/bp0429rg5s0225B878D/7493bb11-e9e5-4279-bc4c-401e020360d6.png?qingflow-expire-time=1757479957&signature=9190a8b9a9b6f8cc543eaf0a1d5aa9c5c22de3a9485c83fac32f8965ef5b916f&qingflow-storage-flag=&qingflow-auth_type=ANONYMOUS"
    # }
    #
    # r=add_vendor_info_internal(test_vendor_data)
    # print(r)
    bank_data = {
        "accName": "测试供应商"
    }
    r = add_Payaccountcreate(bank_data)
    print(r)
